import re
from random import Random  # 用于生成随机码
from django.core.mail import send_mail  # 发送邮件模块
from .models import EmailVerifyRecord  # 邮箱验证model
from django.conf import settings    # setting.py添加的的配置信息

import datetime


# 生成随机字符串
def random_str(randomlength=6):
    """
    随机字符串
    :param randomlength: 字符串长度
    :return: String 类型字符串
    """
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str


# 发送电子邮件

def send_code_email(email,code,send_type="register"):
    """
    发送电子邮件
    :param email: 要发送的邮箱
    :param send_type: 邮箱类型
    :return: True/False
    """
    email_record = EmailVerifyRecord()
    # 将给用户发的信息保存在数据库中
    email_record.code = code
    email_record.email = email
    email_record.send_type = send_type
    email_record.send_time = datetime.datetime.now()
    email_record.save()
    # 初始化为空
    email_title = ""
    email_body = ""
    # 如果为注册类型
    if send_type == "register":
        email_title = "注册激活"
        # email_body = "请点击下面的链接激活你的账号:http://127.0.0.1:8000/active/{0}".format(code)
        email_body = "您的邮箱注册验证码为：{0}, 该验证码有效时间为十五分钟，请及时进行验证。".format(code)
        # 发送邮件
        send_status = send_mail(email_title, email_body, settings.EMAIL_HOST_USER, [email])
        if not send_status:
            return False
    if send_type == "retrieve":
        email_title = "找回密码"
        email_body = "您的邮箱注册验证码为：{0}, 该验证码有效时间为十五分钟，请及时进行验证。".format(code)
        # 发送邮件
        send_status = send_mail(email_title, email_body, settings.EMAIL_HOST_USER, [email])
        if not send_status:
            return False
    return True

def check_email(email):
    regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    if re.fullmatch(regex, email):
        return True
    else :
        return False
def check_code(email,code):
    Email = EmailVerifyRecord.objects.filter(email=email) # 取出数据
    email_code = Email.values('code').order_by('-send_time')[0].get('code') # 取出发送的验证码
    email_time =  Email.filter(code = email_code).values('send_time')[0].get('send_time') # 取出发送的验证码的发送时间
    now_time = datetime.datetime.now() # 获取当前时间
    check_time=now_time - datetime.timedelta(minutes=15)
    if code == email_code: # 比较验证码
        if check_time.__lt__(email_time): # 检查是否在有效时间
            return True
        else:
            return False
    else:
        return False